package hexui;

import hexgame.GameState;
import hexgame.HexMove;
import hexgame.HexPlayer;
import hexui.components.BoardUI;
import hexui.components.Location;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GameWindow extends JFrame {
	private static final long serialVersionUID = 1L;

	GridBagLayout gridBagLayout;
	JButton submitMove = new JButton("Submit move");
	JLabel message = new JLabel();
	JLabel red = new JLabel("Your colour is red");
	BoardUI boardUI;
	LocalPlayer localPlayer;
	GameState gameState;

	public GameWindow(GameState gameState, LocalPlayer localPlayer) {
		this.setTitle("Hex");
		this.boardUI = new BoardUI(gameState);
		this.localPlayer = localPlayer;
		this.gameState = gameState;
		this.gridBagLayout = new GridBagLayout();
		this.setLayout(gridBagLayout);
		this.setSize((gameState.getBoardSize() + 2) * 74 + 150, (gameState.getBoardSize() + 2) * 45 + 160);
		this.setVisible(true);
		this.setResizable(false);
		this.setComponents();
	}

	private void setComponents() {
		
		GridBagConstraints gc = new GridBagConstraints();
		
		gc.anchor = GridBagConstraints.WEST;
		gc.gridx = 0;
		gc.gridy = 0;
		gc.fill = GridBagConstraints.BOTH;
		gc.weightx = 0.3;
		gc.weighty = 0.3;
		gc.insets = new Insets(20,20,20,20);
		this.add(boardUI, gc);
		
		gc.gridx = 1;
		gc.gridy = 0;
		gc.fill = GridBagConstraints.NONE;
		gc.gridheight = 1;
		gc.weightx = 0;
		gc.weighty = 0;
		submitMove.addActionListener(new SubmitListener());
		this.add(submitMove, gc);
		
		gc.insets = new Insets(0,0,10,0);
		gc.anchor = GridBagConstraints.CENTER;
		gc.gridx = 0;
		gc.gridy = 1;
		gc.gridwidth = 2;
		gc.weighty = 0;
		this.add(red, gc);
		
		gc.insets = new Insets(0,0,30,0);
		gc.gridx = 0;
		gc.gridy = 2;
		gc.gridwidth = 2;
		gc.weighty = 0;
		this.setLocalTurn(gameState.isLocalPlayerTurn());
		this.add(message, gc);
	}
	
	public void showMove(HexMove move) {
		boardUI.showMove(move);
	}
	
	public void setLocalTurn(boolean isLocalTurn) {
		if (isLocalTurn) {
			message.setText("It is your turn.");
			submitMove.setEnabled(true);
		} else {
			message.setText("It is the other player's turn.");
			submitMove.setEnabled(false);
		}
	}
	
	class SubmitListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			Location l = boardUI.getSelection();
			
			if(l == null) { 
				return;
			}
			
			// Selection location includes the border, so the location must be offset by 1
			HexMove move = new HexMove(l.x - 1, l.y - 1, HexPlayer.RED_LOCAL);
			
			localPlayer.setCurrentMove(move);
			boardUI.showMove(move);
		}
		
	}
}
